/**
 * 集合数组，根据 id与 pid 返回 树结果对象
 * @param allList
 * @param idKey
 * @param pidKey
 * @param childrenKey
 */
export function parseTree(allList, idKey = 'id', pidKey = 'pid', childrenKey = 'children') {
    //console.log("allList", allList)
    //console.log("idKey", idKey)
    //console.log("pidKey", pidKey)
    //console.log("childrenKey", childrenKey)
    //根数组
    let genArray = gen(allList, idKey, pidKey);
    let genIds = genArray.map((e) => {
        return e[idKey]
    });

    //非根节点数组
    let childArray = [];
    for (let key in allList) {
        let id = allList[key][idKey] + ""
        //id不在根里，说明它是子路由
        if (genIds.indexOf(id) === -1) {
            childArray.push(allList[key])
        }
    }

    //非根节点数组
    let routerArray = [];
    for (let key in genArray) {
        routerArray.push(sort(genArray[key], childArray, idKey, pidKey, childrenKey));
    }
    return routerArray
}

export function getTreeIds(allList, id = 'id', children = 'children', ids = []) {
    for (let key in allList) {

        // 存一下ID
        if (allList[key][id]) {
            ids.push(allList[key][id])
        }

        //如果有children，继续循环
        if (allList[key] [children]) {
            // // // // // //console.log("如果有children，继续循环")
            getTreeIds(allList[key] [children], id, children, ids)
        }
    }
    return ids;
}

export function gen(allList, idKey = 'id', pidKey = 'pid') {
    let ids = [];
    let gen = [];
    for (let key in allList) {
        ids.push(allList[key][idKey] + "")
    }
    for (let key in allList) {
        let pid = allList[key][pidKey] + ""
        //pid在id里面不存在，说明它是根
        if (ids.indexOf(pid) === -1) {
            gen.push(allList[key])
        }
    }
    return gen
}

export function sort(parent_obj, allList, idKey = 'id', pidKey = 'pid', childrenKey = 'children') {
    let child_list = [];
    for (let i = 0; i < allList.length; i++) {
        let now_obj = allList[i];
        let now_pid = now_obj[pidKey];
        //查得到
        if (now_pid.toString() == (parent_obj[idKey] + "")) {
            child_list.push(now_obj); //同级别添加
            sort(now_obj, allList); //继续递归
        }
        //不同级别不做处理
        else {
        }
        if (child_list.length != 0) {
            parent_obj[childrenKey] = child_list;
        }
    }
    return parent_obj
}
